<template>
  <div class="subcontract-registration-manage">
    <div class="model-title-css">
      <div>周进度</div>
    </div>
    <div class="background_wrap public-flex-row">
      <div class="left-box WholeScroll">
        <el-tree class="Public-Tree-Class" :data="leftList" :props="defaultProps" ref='treeData' node-key="id" :highlight-current='true' :default-expanded-keys="defaultTreeKey" @node-click="handleNodeClick"></el-tree>
      </div>
      <div class="right-box">
        <div class="operate_wrap flex">
          <div class="flex-center">
            <el-button type="primary" size="small" class="add buildButtonStyle" v-permission="permission.add" round @click="showDialog('build', '新增')"><i class="iconfont icon-icon_add"></i> 新增
            </el-button>

          </div>
          <div class="flex-right-action-group">

            <el-date-picker size="small" style="width: 240px" v-model="search.yearmonth" type="month" @change="getWeekDefListByMonth" value-format="yyyy-MM" format="yyyy-MM" clearable placeholder="进度日期">
            </el-date-picker>

            <el-select style="float: none;margin: 0; margin-right:15px;" class="select" size="small" v-model="search.weekDefId" value-key="id" typeName filterable clearable placeholder="选择周数" @change="getList(true)">
              <el-option v-for="item in weekTree" :key="item.id" :label="item.weekName" :value="item.id">
              </el-option>
            </el-select>

            <el-button class="search" size="small" @click="getList(true)">
              <i class="iconfont icon-sousuo"></i> 搜索
            </el-button>
          </div>
        </div>
        <div class="list_wrap">
          <el-table :border="true" :row-class-name="tableRowStyleName" :cell-class-name="tableCellStyleName" :header-cell-class-name="tableHeaderCellStyleName" :stripe="true" ref="multipleTable" :data="list" tooltip-effect="dark" @cell-click="cellClick" style="width: 100%; font-family: PingFangSC-Regular; font-size: 14px">
            <el-table-column show-overflow-tooltip prop="xh" align="center" label="序号" width="60">
              <template slot-scope="scope">
                {{ scope.$index + search.pageNo * search.pageSize + 1 }}
              </template>
            </el-table-column>

            <el-table-column show-overflow-tooltip label="标段" prop="sectionName" width="200">
            </el-table-column>

            <el-table-column show-overflow-tooltip label="周期" prop="weekName" width="200">
            </el-table-column>

            <el-table-column show-overflow-tooltip label="周产值（万元）" width="200">
              <template slot-scope="scope">
                <div style="text-align: right;"> {{scope.row.output}}</div>
              </template>
            </el-table-column>

            <el-table-column show-overflow-tooltip label="填报人" prop="createName">
            </el-table-column>

            <el-table-column show-overflow-tooltip label="填报时间" width="170">
              <template slot-scope="scope">
                <div>{{scope.row.createTime?scope.row.createTime.substring(0,10):''}}</div>
              </template>
            </el-table-column>

            <el-table-column show-overflow-tooltip label="操作" min-width="250">
              <template slot-scope="scope">
                <el-button size="mini" class="menu_icon iconfont icon-icon_look action_color1" v-permission="permission.show" @click="handleClickDeal({type:'show',name:'查看',detailId:scope.row.id})">&nbsp;查看</el-button>
                <el-button size="mini" class="menu_icon iconfont icon-xiugai-copy action_color1" v-permission="permission.edit" @click="handleClickDeal({type:'update',name:'修改',detailId:scope.row.id})">&nbsp;修改</el-button>
                <el-button size="mini" class="menu_icon iconfont icon-shanchu action_color2" v-permission="permission.del" @click="handleClickDeal({type:'delete',name:'删除',detailId:scope.row.id})">&nbsp;删除</el-button>
              </template>

            </el-table-column>
          </el-table>
          <el-pagination style="float: right; margin-top: 30px" layout="prev, pager, next" :page-size="search.pageSize" :total="search.total" :current-page="search.pageNo + 1" :prev-text="tablePaginationPrev" :next-text="tablePaginationNext" @current-change="paginationChange">
          </el-pagination>
        </div>
      </div>
    </div>

    <Detail :postDetail="postDetailData" @reloadList="getList(true)"></Detail>

  </div>
</template>

<script>
import {
  tableRowStyleGol,
  tableCellStyleGol,
  tableHeaderCellStyleGol,
  doCreateObject
} from '@/utils/publicFun'

import msgUtil from '@/utils/msgUtil'
import projectSectionInfo from '@/api/buss/common'
import WorkFlowBtn from '@/components/WorkFlow/table'
import WfStatus from '@/components/WorkFlow/status/index'

import progressWeekly from '@/api/buss/weeklyProgress'
import publicSearchData from '@/mixins/publicSearchData'
export default {
  mixins: [publicSearchData],
  name: `demo`,
  components: {
    Detail: require(`./weekly-report-detail`).default,
    WorkFlowBtn,
    WfStatus,
  },
  data() {

    return {
      leftList: [],
      processDialog: false,
      defaultTreeKey: [],
      defaultProps: {
        children: 'children',
        label: 'name',
      },
      chooseTreeData: {},
      permission: {
        add: ['100', '1001069:add'],
        show: ['100', '1001069:show'],
        edit: ['100', '1001069:edit'],
        del: ['100', '1001069:del'],
      },

      tableRowStyleName: tableRowStyleGol,
      tableCellStyleName: tableCellStyleGol,
      tableHeaderCellStyleName: tableHeaderCellStyleGol,
      tablePaginationPrev: '上一页',
      tablePaginationNext: '下一页',
      hasAdd: false, //是否有新增权限
      loading: false,
      //  当前查看的文件列表
      nowFileList: [],
      showFileDialog: false,
      list: [{}, {}, {}, {}],
      title: '人员',

      addSectionId: '', // 新增带过去的标段Id
      weekTree: [],
      // 搜索参数
      search: {
        //pageIndex: 0,
        pageNo: 0,
        pageSize: 10,
        //pageSum: 0,
        total: 0,
        sectionId: '',
        projectId: '',
        yearmonth: '',


      },

      // 向详情子组件的传值
      postDetailData: {
        show: false,
        type: 'build',
        typeName: '新增',
      },
      // 向详情子组件的传值
      treeEditDialogData: {
        show: false,
        nowTreeData: []
      },

    }
  },
  mounted() {
    this.initData()
  },
  methods: {

    approve(obj) {
      this.postDetailData = {
        show: true,
        type: 'approve',
        typeName: '审核',
        detailId: obj.id,
      }
    },
    edit(obj) {
      this.postDetailData = {
        show: true,
        type: 'edit',
        typeName: '编辑',
        detailId: obj.id,
      }
    },
    detail(obj) {
      this.postDetailData = {
        show: true,
        type: 'check',
        typeName: '查看',
        detailId: obj.id,
      }
    },
    del(obj) {
      if (obj.id === '') {
        msgUtil.error2('请先选择要删除的记录！')
        return
      }
      msgUtil.confirm('确认删除该条数据?').then(res => {
        let idlist = []
        idlist.push(obj.id)
        let param = {
          ids: idlist
        }
        progressWeekly.del(param).then(res => {
          if (res.code === 200) {
            msgUtil.success2('删除成功!')
            this.getList()
          } else {
            msgUtil.error2(res.data.message)
          }
        })
      })
    },



    initData() {
      projectSectionInfo.getLeftProjectTree().then(res => {
        if (res.code === 200) {
          this.$set(this, 'leftList', res.data)

          if (this.leftList.length > 0) {
            this.$nextTick(() => {
              if (this.$headerSearch) {
                if (this.changeHeaderProject) {
                  this.$refs['treeData'].setCurrentKey(this.changeHeaderProject);
                  if (this.defaultTreeKey) {
                    this.defaultTreeKey.push(this.changeHeaderProject)
                  }
                  this.handleNodeClick({
                    id: this.changeHeaderProject
                  })
                } else {
                  this.defaultTreeKey.push(this.leftList[0].id)
                  this.$refs['treeData'].setCurrentKey(this.leftList[0].id);
                  if (this.defaultTreeKey) {
                    this.defaultTreeKey.push(this.leftList[0].id)
                  }
                  this.handleNodeClick(this.leftList[0])
                }
              } else {
                this.defaultTreeKey.push(this.leftList[0].id)
                this.$refs['treeData'].setCurrentKey(this.leftList[0].id);
                if (this.defaultTreeKey) {
                  this.defaultTreeKey.push(this.leftList[0].id)
                }
                this.handleNodeClick(this.leftList[0])
              }
            })
          } else {
            this.list = []
          }
        } else {
          this.$messageError(res.data.message)
        }
      }).catch(() => {
        this.$messageError('获取项目标段树失败')
      })
    },

    // 事件处理的api请求
    sealDealHttp(url, query, param, callback) {
      this.$httpPost(url + query, param)
        .then((res) => {
          if (res.status === 1) {
            if (callback) callback(res)
            // 重新获取数据
            setTimeout(() => {
              this.getList(true)
            }, 1000)
          } else {
            this.$messageError(res.message)
          }
        })
        .catch((res) => {
          console.log('请求出现错误', res)
          console.log(res)
        })
    },
    handleNodeClick(data) {
      this.search.projectId = '';
      this.search.sectionId = '';

      console.log(data);
      if (data.type == 'projectId') {
        this.search.projectId = data.id;
      }
      if (data.type == 'sectionId') {
        this.search.sectionId = data.id;
      }
      this.getList(true)
    },
    // 格式化表单数据
    formatter(row, column) {
      let array = column.property.split('.')
      let result
      array.forEach((item, i) => {
        result = result === undefined ? row[item] : result[item]
      })
      if (result === '' || result === undefined) {
        return '--'
      } else {
        return result
      }
    },
    // 列表的操作流程
    handleClickDeal(res) {
      let type = res.type
      let detailId = res.detailId
      this.boundContractId = detailId
      // console.log(res)
      switch (type) {
        // 查看
        case 'show':
          // 显示详情弹窗
          this.showDetailDialog(type, {
            detailId: detailId,
          })
          break
        // 修改
        case 'update':
          // 显示详情弹窗
          this.showDetailDialog(type, {
            detailId: detailId,
          })
          break
        // 删除
        case 'delete':
          if (detailId === '') {
            this.$messageError('请先选择要删除的记录！')
            return
          }
          this.$confirm('确定是否删除？', '提示', {
            confirmButtonClass: 'iconfont icon-icon_ok',
            cancelButtonClass: 'iconfont icon-icon_cancel',
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'info'
          }).then(() => {
            this.$httpPost(`/buss/progressWeekly/delete`, { ids: detailId.split(',') }).then((res) => {
              if (res.code === 200) {
                this.$message.success("删除成功")
                // 重新获取数据
                setTimeout(() => {
                  this.getList(true)
                }, 1000)
              } else {
                this.$messageError(res.msg)
              }
            }).catch((res) => {
              console.log('请求出现错误', res)
            })
          })
            .catch(() => {
            })
          console.log('请求出现错误')
          break
      }
    },
    showDetailDialog(flag, params) {
      console.log(flag, params)
      switch (flag) {
        case 'build':
          this.postDetailData = {
            show: true,
            type: 'build',
            params: params
          }
          break
        case 'update':
          this.postDetailData = {
            show: true,
            type: 'edit',
            params: params
          }
          break
        //查看
        case 'show':
          this.postDetailData = {
            show: true,
            type: 'check',
            params: params
          }
          break
      }
    },
    // 点击单元格
    cellClick(row, column, cell, event) {
      // if (column.property === 'sectionName') {
      //   this.detail(row)
      // }
    },


    /**
     * 获取周下拉
     * 根据月份
     */
    getWeekDefListByMonth() {
      this.getList(true)
      if (!this.search.yearmonth) {
        this.search.weekDefId = ''
        this.weekTree = []
        return;
      }
      // 检查周数分解
      let postData = {
        planMonth: this.search.yearmonth,
      }
      this.$httpPost(`buss/progressscheduleWeek/getWeekDefListByMonth`, postData).then(res => {
        if (res.code === 200) {
          this.weekTree = res.data
        } else {
          msgUtil.error2(res.data.message)
        }
      }).catch((res) => {
        console.log(res)
      }).finally((response) => {
      })

    },
    // 获取列表 api
    getList(reload) {
      if (reload) {
        this.search.pageIndex = 0
      }
      this.list = []
      let param = {
        pageNo: this.search.pageNo,
        pageSize: this.search.pageSize,
        projectId: this.search.projectId,
        sectionId: this.search.sectionId,
        yearmonth: this.search.yearmonth,
        weekDefId: this.search.weekDefId,
      }
      this.$httpPost(`buss/progressWeekly/listPage`, param).then(res => {
        if (res.code == 200) {
          this.list = res.data.content
          this.search.total = res.data.totalElements
        } else {
          msgUtil.error2(res.data.message)
        }
      })
    },

    // 切换列表
    paginationChange(index) {
      this.search.pageNo = index - 1
      this.getList()
    },
    /*  操作 */
    showDialog(type, typeName, detailId) {
      console.log(this.search.sectionId);
      if (!this.search.sectionId) {
        this.$messageWarning("请先选中要加的标段")
        return;
      }

      switch (type) {
        case 'build':
          this.postDetailData = {
            show: true,
            type: type,
            typeName: typeName,
            detailId: '',
            addSectionId: this.search.sectionId
          }
          break
        case 'edit':
          this.postDetailData = {
            show: true,
            type: type,
            typeName: typeName,
            detailId: detailId
          }
          break
        case 'check':
          this.postDetailData = {
            show: true,
            type: type,
            typeName: typeName,
            detailId: detailId,
          }
          break
        case 'delete':
          if (detailId === '') {
            msgUtil.error2('请先选择要删除的记录！')
            return
          }
          msgUtil.confirm('确认删除该条数据?').then(res => {
            let idlist = []
            idlist.push(detailId)
            let param = {
              ids: idlist
            }
            progressWeekly.del(param).then(res => {
              if (res.status === 1) {
                msgUtil.success2('删除成功!')
                this.getList()
              } else {
                msgUtil.error2(res.data.message)
              }
            })
          })
          break

      }
    },




  },
}
</script>

<style scoped lang="scss">
.model-title-css {
  display: flex;
  flex-direction: row;
  align-items: center;
}
.list_wrap {
  margin-top: 20px;
}
.left-box {
  min-width: 220px !important;
  max-width: 350px !important;
  max-height: calc(100vh - 200px);
  border-right: 1px #e2e8ec solid;
  overflow: auto;
  p {
    cursor: pointer;
    font-size: 14px;
  }
}
.right-box {
  width: calc(100% - 220px);
  padding-left: 15px;
  flex-grow: 1;
}
</style>
